var $form = $("#validation-form");
var treeObj;
var treeSetting = {
    view: {
        addHoverDom: function (treeId, treeNode) {
            var aObj = $("#" + treeNode.tId + "_a");
            if ($("#btnSpan_" + treeNode.id).size() != 0) {
                return;
            }
            var btns =  [
                "<a type='button' id='diyBtn1_" + treeNode.id + "' title='向上移动' onfocus='this.blur();'><i class='glyphicon glyphicon-circle-arrow-up'></i></a>",
                "<a type='button' id='diyBtn2_" + treeNode.id + "' title='向下移动' onfocus='this.blur();'><i class='glyphicon glyphicon-circle-arrow-down'></i></a>",
                "<a type='button' id='diyBtn3_" + treeNode.id + "' title='添加'     onfocus='this.blur();'><i class='glyphicon glyphicon-plus-sign'></i></a>",
                "<a type='button' id='diyBtn4_" + treeNode.id + "' title='删除'     onfocus='this.blur();'><i class='glyphicon glyphicon-remove'></i></a>"
            ];
            aObj.append("<span id='btnSpan_" + treeNode.id + "' >" + btns.join("") + "</span>");
            var upBtn = $("#diyBtn1_" + treeNode.id);
            if (upBtn) {
                upBtn.bind("click", function () {
                    var brother = treeNode.getPreNode();
                    if (brother == null) {
                        $.messager.alert("已经是第一个节点，不能向上移动");
                        return;
                    }
                    treeJs.move(treeNode.getPreNode(), treeNode);
                });
            }
            var downBtn = $("#diyBtn2_" + treeNode.id);
            if (downBtn) {
                downBtn.bind("click", function () {
                    var brother = treeNode.getNextNode();
                    if (brother == null) {
                        $.messager.alert("已经是最后一个节点，不能向下移动");
                        return;
                    }
                    treeJs.move(treeNode, treeNode.getNextNode());
                });
            }

            //添加
            var addBtn = $("#diyBtn3_" + treeNode.id);
            if (addBtn) {
                addBtn.bind("click", function (e) {//“添加”按钮点击事件
                    treeJs.add(treeNode);
                    e.stopPropagation();
                });
            }

            var deleteBtn = $("#diyBtn4_" + treeNode.id);
            if (deleteBtn) {
                deleteBtn.bind("click", function (e) {
                    treeJs.delete(treeNode);
                    e.stopPropagation();
                });
            }
        },
        removeHoverDom: function (treeId, treeNode) {
            $("#btnSpan_" + treeNode.id + " a").unbind().remove();
            $("#btnSpan_" + treeNode.id).unbind().remove();
        }
    },
    async: {
        enable: true,
        url: ctx + "/resource/list",
        autoParam: ["id"],
        dataFilter: function (treeId, parentNode, childNodes) {
            if (!childNodes) return null;
            for (var i = 0, l = childNodes.length; i < l; i++) {
                childNodes[i].name = childNodes[i].name.replace(/\.n/g, '.');
            }
            return childNodes;
        }
    },
    edit: {
        showRemoveBtn: false,
        enable: true,
        showRenameBtn: false
    },
    callback: {
        onClick: function (event, treeId, treeNode) {
            $form.get(0).reset();
            $form.hide();
            if (treeNode.level == 0) {
                return;
            }
            var parentName = treeNode.getParentNode().name;
            var parentId = treeNode.getParentNode().id;
            $("[name='parentId']").val(parentId);
            $("[name='parentName']").val(parentName);
            $("[name='id']").val(treeNode.id);
            $("[name='name']").val(treeNode.name);
            $("[name='url']").val(treeNode.url);
            $("[name='permissionValue']").val(treeNode.permissionValue);
            $("[name='permissionKey']").val(treeNode.permissionKey);
            $("[name='type'][value='" + treeNode.type + "']").prop("checked", true);
            $form.show();
            $("#saveBtn").unbind().bind("click", function () {
                treeJs.save(treeNode, "edit");
            });
            event.stopPropagation();
        }
    }
};
$(function () {
    $.fn.zTree.init($("#treeView"), treeSetting);
    treeObj = $.fn.zTree.getZTreeObj("treeView");
});


if (typeof  treeJs == 'undefined') {
    var treeJs = {};
    /**移动*/
    treeJs.move = function (treeNode1, treeNode2) {
        $.getJSON(ctx + "/resource/sort", {id1: treeNode1.id, id2: treeNode2.id}, function (data) {
            if (data && data.status == "SUCCESS") {
                treeObj.moveNode(treeNode1, treeNode2, "prev");
            } else {
                $.messager.alert(data ? data.body : "系统错误,请稍后再试");
            }
        });
    }
    /**保存*/
    treeJs.save = function (treeNode, type) {
        if (!treeJs.checkForm().form()) {
            return false;
        }
        if (type == "edit") {
            $.getJSON(ctx + "/resource/update", $form.serialize(), function (data) {
                $.messager.alert(data.body);
                if (data && data.status == "SUCCESS") {
                    treeNode.name = $("[name='name']").val();
                    treeNode.url = $("[name='url']").val();
                    treeNode.permissionkey = $("[name='permissionKey']").val();
                    treeNode.permissionValue = $("[name='permissionValue']").val();
                    treeNode.type = $("[name='type']:checked").val();
                    treeObj.updateNode(treeNode);
                }
            });
        }
        else {
            $.getJSON(ctx + "/resource/insert", $form.serialize(), function (data) {
                $.messager.alert(data.body);
                if (data && data.status == "SUCCESS") {
                    $("[name='id']").val(data.data);//保存后返回ID
                    var newNode = {
                        name: $("[name='name']").val(),
                        id: data.data,
                        url: $("[name='url']").val(),
                        permissionKey: $("[name='permissionKey']").val(),
                        permissionValue: $("[name='permissionValue']").val(),
                        type: $("[name='type']:checked").val()
                    };
                    newNode = treeObj.addNodes(treeNode, newNode);
                    treeObj.selectNode(newNode);
                    $form.hide();
                }
            });
        }
    }
    /**添加按钮*/
    treeJs.add = function (treeNode){
        $form.get(0).reset();//清空表单
        var parentName = treeNode.name;//这里是被点击的节点的名称
        var parentId = treeNode.id;//这里是被点击的节点的ID
        $("[name='parentName']").val(parentName);
        $("[name='parentId']").val(parentId);
        $("[name='id']").val("");
        $(":radio").prop("checked", false);
        $form.show();
        $("#saveBtn").unbind().bind("click", function () {
            treeJs.save(treeNode, "new");
        });
    }

    treeJs.delete=function (treeNode){
        var len = treeNode.children ? treeNode.children.length : 0;
        //ajax查询下级count
        if (len == 0) {

        }
        if (len > 0) {
            $.messager.alert("请先删除子节点");
            return;
        } else {
            $.messager.confirm("确认要删除" + treeNode.name + "吗?", function (ck) {
                if (ck) {
                    //隐藏右侧表单
                    if ($("[name='id']").val() == treeNode.id) {
                        $form.hide();
                    }
                    $.getJSON(ctx + "/resource/delete", {id: treeNode.id}, function (data) {
                        if (data && data.status == "SUCCESS") {
                            var pNode = treeNode.getParentNode();
                            treeObj.removeNode(treeNode);
                            var childLength = pNode.children.length;
                            if (childLength == 0) {
                                pNode.isParent = false;
                                treeObj.updateNode(pNode);
                            }
                            $.messager.alert("删除成功");
                        }
                    });
                }
            });
        }
    }

    treeJs.checkForm=function (){
        return $('#validation-form').validate({
            rules: {
                name: {
                    required: true
                },
                permissionKey: {
                    pattern: "(/(\\w+|\\\*{1,2})((\\.jsp)|(\\.html))?)+"
                },
                permissionValue: {
                    //pattern: "perms\\\[\\w+[:\\w+]+\\\]"
                   // pattern:"\\w+(\:\\w+)"
                }
            }
        });
    }
}
